package com.ywicc.usblibs.utils;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

/**
 * author : zhouxuan77
 * e-mail : zhouxuan77@163.com
 * time   : 2022/03/21
 * desc   : USB 权限获取类
 * version: 1.0
 */
public class UsbPermissionUtils {

    private final static String TAG = "UsbPermissionUtils";

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    private final Context context;
    private UsbManager usbManager;
    private OnUsbPermissionListener onUsbPermissionListener;

    public UsbPermissionUtils(Context context) {
        this.context = context;
    }

    /**
     * 判断是否成功获取权限
     * <p>
     * 通过接口返回后续 USB 操作所需的 UsbManager 和 UsbDevice
     *
     * @param onUsbPermissionListener UsbPermissionUtils.OnPermissionResultListener 对象
     */
    @SuppressLint("UnspecifiedImmutableFlag")
    public void checkPermission(OnUsbPermissionListener onUsbPermissionListener) {
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

        this.onUsbPermissionListener = onUsbPermissionListener;

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        context.registerReceiver(receiver, filter);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);

        for (UsbDevice usbDevice : usbManager.getDeviceList().values()) {
            if (usbManager.hasPermission(usbDevice) && onUsbPermissionListener != null) {
                Log.v(TAG, "获取 USB 权限成功");

                onUsbPermissionListener.onResult(usbManager, usbDevice);
            } else {
                Log.v(TAG, "无 USB 权限，正在获取");

                usbManager.requestPermission(usbDevice, pendingIntent);
            }
        }
    }

    /**
     * 设置广播，接收权限请求状态
     * <p>
     * 通过接口成功获取相应的对象后，及时调用 UsbPermission.stopReceiver() 结束广播
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (usbDevice != null && onUsbPermissionListener != null) {
                            Log.v(TAG, "获取 USB 权限成功");

                            onUsbPermissionListener.onResult(usbManager, usbDevice);
                        }
                    } else {
                        try {
                            throw new Exception("Permission Cancel");
                        } catch (Exception e) {
                            e.printStackTrace();

                            Log.v(TAG, "USB 权限弹窗被取消");
                        }
                    }
                }
            }
        }
    };

    /**
     * 当获取完成 USB 权限后，及时注销广播
     */
    public void stopReceiver() {
        context.unregisterReceiver(receiver);
    }

    /* 接口区域 */

    public interface OnUsbPermissionListener {
        void onResult(UsbManager usbManager, UsbDevice usbDevice);
    }
}
